<?php
/*
Plugin Name: Settings API Exmaple
Plugin URI: http://wordpress.org/extend/plugins/hello-dolly/
Description: Settings API Exmaple plugin.
Author: Matt Mullenweg
Version: 1.6
Author URI: http://ma.tt/
*/

// Add a menu for our option page
add_action('admin_menu', 'jtw_myplugin_add_page');
function jtw_myplugin_add_page() {
	add_options_page( 'My Plugin', 'My Plugin', 'manage_options', 
		'jtw_myplugin', 'jtw_myplugin_option_page');
}

// Draw the options page
function jtw_myplugin_option_page() { ?>
	<div class="wrap">
		<?php screen_icon(); ?>
		<h2>My Awesome Plugin!</h2>
		<form action="options.php" method="post">
			<?php settings_fields('jtw_myplugin_options'); ?>
			<?php do_settings_sections('jtw_myplugin'); ?>
			<input name="Submit" type="submit" value="Save Changes" />
		</form>
	</div>
	<?php	
}

// Register and define the settings
add_action('admin_init', 'jtw_myplugin_admin_init');
function jtw_myplugin_admin_init() {
	register_setting( 
		'jtw_myplugin_options', 
		'jtw_myplugin_options', 
		'jtw_myplugin_validate_options' 
		);
	add_settings_section( 
		'jtw_myplugin_main', 
		'My Plugin Settings', 
		'jtw_myplugin_section_text', 
		'jtw_myplugin'); 
	add_settings_field( 
		'jtw_myplugin_text_string', 
		'Enter text here', 
		'jtw_myplugin_setting_input', 
		'jtw_myplugin', 
		'jtw_myplugin_main' );
	// Add Settings to the Privacy Page
	register_setting(
		'privacy',
		'jtw_myplugin_options',
		'jtw_myplugin_validate_options'
		);
	add_settings_section(
		'jtw_myplugin_options',
		'My Plugin Settings',
		'jtw_myplugin_section_text',
		'privacy'
		);
	add_settings_field(
		'jtw_myplugin_text_string',
		'Enter Text Here',
		'jtw_myplugin_setting_input',
		'privacy',
		'jtw_myplugin_options'
		);
}

// Draw the secion header
function jtw_myplugin_section_text() {
	echo '<p>Enter your settings here.</p>';
}

// Display and fill the form field
function jtw_myplugin_setting_input() {
	// get option 'text_string' value from the database
	$options = get_option( 'jtw_myplugin_options' );
	$text_string = $options['text_string'];
	// echo the field
	echo "<input id='text_string' name='jtw_myplugin_options[text_string]' 
		type='text' value='$text_string' />";
}

// Validate user input (we want text only)
function jtw_myplugin_validate_options( $input ) {
	$valid = array();
	$valid['text_string'] = preg_replace(
		'/[^a-zA-Z]/',
		'',
		$input['text_string'] );
	
	if( $valid['text_string'] != $input['text_string'] ) {
		add_Settings_error(
			'jtw_my_plugin_text_string',
			'jtw_myplugin_texterror',
			'Incorrect value Entered!',
			'error'
			);
	}
	
	return $valid;
}

?>